package com.reverie.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.reverie.common.pojo.CommonResult;
import com.reverie.entity.Org;
import com.reverie.entity.User;
import com.reverie.service.IOrgService;
import com.reverie.service.IUserService;
import lombok.AllArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@AllArgsConstructor
public class OrgController {

    private final IOrgService orgService;
    private final IUserService userService;

    @PostMapping("/admin/v1/org/list")
    public CommonResult<List<Org>> list(@RequestBody Org org){
        Object loginId = StpUtil.getLoginId();
        User user = userService.getById(loginId.toString());

        QueryWrapper<Org> queryWrapper = new QueryWrapper<>();
        if(org.getParentId()!= null){
            queryWrapper.lambda().eq(Org::getParentId, org.getParentId());
        }
        if(StringUtils.hasLength(org.getName())){
            queryWrapper.lambda().eq(Org::getName, org.getName());
        }
        queryWrapper.lambda()
                .eq(Org::getId, user.getOrgId())
                .or().in(Org::getParentId, user.getOrgId());
        return CommonResult.data(orgService.list(queryWrapper));
    }

    @PostMapping("/admin/v1/org/getTree")
    public CommonResult<List<Tree<String>>> getOrgTree(){
        return CommonResult.data(orgService.getOrgTree());
    }

    @PostMapping("/admin/v1/org/save")
    public CommonResult<Boolean> save(@RequestBody Org org){
        return CommonResult.data(orgService.saveOrUpdate(org));
    }

    @PostMapping("/admin/v1/org/delete")
    public CommonResult<Boolean> delete(@RequestBody Org org){
        return CommonResult.data(orgService.removeById(org.getId()));
    }
}
